/******************************************************************************
 * Copyright (C) 2012 ShenZhen ComTop Information Technology Co.,Ltd
 * All Rights Reserved.
 * 本软件为深圳康拓普开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
 * 复制、修改或发布本软件.
 *****************************************************************************/

package com.code.common.nio;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;

import com.code.common.utils.SerializableUtil;

/**
 * 监控数据传输到WEB平台
 * 
 * @author 李鹏
 * @since 1.0
 * @version 2012-12-6 陈大周
 */
public class TransferingDataHelp {
    
    private final static int TransferPort = 8888;
    
    private final static Logger LOG = Logger.getLogger(TransferingDataHelp.class);
    
    /**
     * 构造函数
     * 
     * @param blockQueue
     */
    public TransferingDataHelp() {
    }
    
    /**
     * 监控数据传输
     * 
     * @param serverIp
     * @param port
     */
    public static void sendData(String serverIp, Object CON_MAP) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open();
            SocketAddress socketAddress = new InetSocketAddress(serverIp, TransferPort);
            socketChannel.connect(socketAddress);
            byte[] bytes = SerializableUtil.toBytes(CON_MAP);
            ByteBuffer buffer = ByteBuffer.wrap(bytes);
            socketChannel.write(buffer);
            socketChannel.socket().shutdownOutput();
        } catch (Exception ex) {
            LOG.error("NIO连接不成功,请检查NUMEN服务器端的NIO是否启动,或者本地的NIO端口是否配置正确!");
        } finally {
            try {
                socketChannel.close();
            } catch (Exception ex) {
            }
        }
    }
    
    /**
     * 监控数据传输
     * 
     * @param serverIp
     * @param port
     */
    public static void sendData(String serverIp, int port, Object CON_MAP) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open();
            SocketAddress socketAddress = new InetSocketAddress(serverIp, port);
            socketChannel.connect(socketAddress);
            byte[] bytes = SerializableUtil.toBytes(CON_MAP);
            ByteBuffer buffer = ByteBuffer.wrap(bytes);
            socketChannel.write(buffer);
            socketChannel.socket().shutdownOutput();
        } catch (Exception ex) {
            LOG.error("NIO连接不成功,请检查NUMEN服务器端的NIO是否启动,或者本地的NIO端口是否配置正确!");
        } finally {
            try {
                socketChannel.close();
            } catch (Exception ex) {
            }
        }
    }
    
}